const jwt = require('jsonwebtoken');
// 校验传入的数据是否合法
const errorType = require('../constant/errTypes');
const connections = require('../app/database')
const service = require('../services/users.service')
const AuthService = require('../services/auth.service')
const passwordHandler = require('../utils/passwordHandler')
const {public_key} = require('../app/config')
const verifyAuth = async (ctx, next) => {
  //校验密码
  console.log('verifyAuth校验登录时的密码是否正确')
  const {name, password} = ctx.request.body;
  if (!name || !password) {
    const error = new Error(errorType.NAME_OR_PASSWORD_IS_INVALID);
    return ctx.app.emit('error', error, ctx);
  }
  // 查询数据库中是否存在该用户
  const result = await service.getUserByName(name);
  const user = result[0];
  if (!user) {
    const error = new Error(errorType.NAME_OR_PASSWORD_IS_NOT_EXIST);
    return ctx.app.emit('error', error, ctx);
  }
  if (result[0].password !== passwordHandler(password)) {
    const error = new Error(errorType.NAME_OR_PASSWORD_IS_NOT_MATCH);
    return ctx.app.emit('error', error, ctx);
  }
  ctx.user = user;
  await next();
}

//////////////////////////////////////////////////////////////////////////////////////////////
const verifyLogin = async (ctx, next) => {
  console.log("验证是否有token的middlewares");
  const authorization = ctx.request.header.authorization;
  if (!authorization) {
    const error = new Error(errorType.TOKEN_IS_INVALID);
    return ctx.app.emit('error', error, ctx);
  }
  const token = authorization.replace('Bearer ', '');
  // 校验token
  try {
    ctx.user = jwt.verify(token, public_key, {
      algorithms: ['RS256']
    });
    await next();
  } catch (err) {
    const error = new Error(errorType.TOKEN_IS_INVALID);
    return ctx.app.emit('error', error, ctx);
  }
}
const verifyPermission = async (ctx, next) => {
  console.log("验证是否有修改权限的middlewares");
  const [resourceKey] = Object.keys(ctx.params);
  const tableName = resourceKey.replace("Id", '');
  const resourceId = ctx.params[resourceKey];
  console.log(tableName, resourceId);
  // 校验权限 将得到的id与数据库中users的id进行比对
  const {id} = ctx.user;
  // const {momentId} = ctx.params;
  // 查询数据库中是否存在该用户
  try {
    const isPermission = await AuthService.checkResource(tableName, resourceId, id);
    console.log("isPermission", isPermission);
    if (!isPermission) {
      const error = new Error(errorType.UNPERMISSION);
      return ctx.app.emit('error', error, ctx);
    }
    await next();
  } catch (err) {
    const error = new Error(errorType.UNPERMISSION);
    return ctx.app.emit('error', error, ctx);
  }
}
// //验证标签是否存在
// const verifyLabelExists = async (ctx,next) => {
//   const label = ctx.request.body.label;
//   const result = await service.getLabelByName(label);
//   if (result.length <= 0) {
//     const error = new Error(errorType.LABEL_NOT_EXIST);
//     return ctx.app.emit('error', error, ctx);
//   }
//   await next();
// }
module.exports = {verifyAuth, verifyLogin, verifyPermission, };